<?php

class Kzend_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup($req)
    {
        $configs = array();
        $confFile = APPLICATION_PATH . "/configs/auth_controllers.ini";
        if (file_exists($confFile)) {
            $ini = new Zend_Config_Ini($confFile);
            $configs = $ini->toArray();
        }

        // Skip for ignore actions
        $currentModule = $req->getModuleName();
        $currentController = $req->getControllerName();
        $currentAction = $req->getActionName();

        foreach ($configs as $confMod => $val1) {
            if (is_array($val1)) {
                foreach ($val1 as $confCont => $val2) {
                    if (is_array($val2)) {
                        foreach ($val2 as $confAct => $val3) {
                            if ($currentModule == $confMod && $currentController == $confCont && ($currentAction == $confAct || $confAct == "ALL")) {
                                return;
                            }
                        }
                    }
                }
            }
        }
        
        $auth = Zend_Auth::getInstance();

        if (!$auth->hasIdentity()) {
            $noAuthDispatchFor = $configs['noauth_dispatch_for'];
            list($mod, $con, $act) = explode(".", $noAuthDispatchFor);

            if (Zend_Session::isStarted()) {
                $sess = new Zend_Session_Namespace("Kzend_Auth");
                $sess->currentModule = $req->getModuleName();
                $sess->currentController = $req->getControllerName();
                $sess->currentAction = $req->getActionName();
            }

            $frontController = Zend_Controller_Front::getInstance();
            $response = $frontController->getResponse();
            $response->setRedirect($frontController->getBaseUrl() . "/" . $mod . "/" . $con . "/" . $act . "/");
            $response->sendHeaders();
            exit;
        }
    }
}
